package com.xht.runner;

import com.xht.constants.SystemConstants;
import com.xht.domain.entity.Article;
import com.xht.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * bean初始化后 便会执行的方法
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 将文章访问量 提前存储到redis中
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        //查询 文章信息
        List<Article> articles = articleMapper.selectList(null);
        //先将文章信息中的浏览量,存储在哈希中 ,key--id  value--viewCount
        Map<String, String> articleCountMap = new HashMap<>();
        for (Article article : articles) {
            articleCountMap.put(article.getId().toString(), article.getViewCount().toString());
        }
        //在将该哈希表 存储在redis 上

        stringRedisTemplate.opsForHash().putAll(SystemConstants.VIEW_COUNT, articleCountMap);


    }
}
